from numpy import *
import numpy as np

def generateDataSet(num_samples=100, num_features=1, noise_level=0.1):
    """
    生成模拟数据集
    num_samples: 样本数量
    num_features: 特征数量
    noise_level: 噪声水平
    """
    # 设置随机种子以保证结果可重现
    random.seed(42)
    
    # 生成特征矩阵
    dataMat = []
    labelMat = []
    
    # 生成真实的权重向量（不包括偏置项）
    true_weights = random.randn(num_features) * 2
    
    # 生成偏置项
    bias = random.randn() * 3
    
    for i in range(num_samples):
        # 生成特征向量
        x = random.randn(num_features) * 5
        dataMat.append(list(x))
        
        # 计算真实标签：y = w*x + b + 噪声
        true_y = sum(true_weights * x) + bias
        noise = random.randn() * noise_level
        label = true_y + noise
        
        labelMat.append(float(label))
    
    print(f"生成数据集: {num_samples}个样本, {num_features}个特征")
    print(f"真实权重: {true_weights}, 真实偏置: {bias:.4f}")
    
    return dataMat, labelMat

def standRegres(xArr, yArr):
    """
    标准线性回归
    """
    xMat = mat(xArr); yMat = mat(yArr).T
    xTx = xMat.T * xMat
    if linalg.det(xTx) == 0.0:
        print("This matrix is singular, cannot do inverse")
        return
    ws = xTx.I * (xMat.T * yMat)
    return ws

# 使用示例
if __name__ == "__main__":
    # 生成数据集
    dataMat, labelMat = generateDataSet(num_samples=100, num_features=2)
    
    # 进行线性回归
    ws = standRegres(dataMat, labelMat)
    print(f"回归系数: {ws}")
    
    # 计算预测值和R²分数
    xMat = mat(dataMat)
    yMat = mat(labelMat).T
    yPred = xMat * ws
    
    # 计算R²
    corr = corrcoef(yPred.T, yMat.T)
    print(f"预测值与真实值的相关系数: {corr[0,1]:.4f}")